package com.lbjhan.rpc.consumer.handler;

import com.lbjhan.rpc.common.RpcRequest;
import com.lbjhan.rpc.common.RpcResponse;
import com.lbjhan.rpc.serializer.ISerializer;
import com.lbjhan.rpc.serializer.KryoSerializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
import io.netty.handler.codec.ReplayingDecoder;

import java.util.List;

public class RpcNettyClientSerializerDecoder extends ReplayingDecoder {

    private ISerializer serializer;
    public RpcNettyClientSerializerDecoder(ISerializer serializer){
        this.serializer = serializer;
    }

    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        int length = byteBuf.readInt();
        byte[] bytes = new byte[length];
        byteBuf.readBytes(bytes);
        Object obj = serializer.deserialize(bytes, RpcResponse.class);
        list.add(obj);
    }
}
